package cn.edu.scau.cmi.linjinyong.fxml.springMybatis;

import cn.edu.scau.cmi.linjinyong.fxml.mybatis.StudentData;
import cn.edu.scau.cmi.linjinyong.fxml.mybatis.TeacherData;
import cn.edu.scau.cmi.linjinyong.mybatis.dao.StudentDao;
import cn.edu.scau.cmi.linjinyong.mybatis.dao.TeacherDao;
import cn.edu.scau.cmi.linjinyong.mybatis.domain.Student;
import cn.edu.scau.cmi.linjinyong.mybatis.domain.Teacher;
import cn.edu.scau.cmi.linjinyong.mybatis.factory.SessionFactory;
import cn.edu.scau.cmi.linjinyong.spring.ApplicationContextFactory;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SpringMybatisController {
    @FXML
    private Button modifyButton;
    @FXML
    private Button deleteButton;
    @FXML
    private Button chooseTeacherButton;
    @FXML
    private Button chooseStudentButton;
    @FXML
    private TableView<StudentData> studentTableView;
    @FXML
    private TableView<TeacherData> teacherTableView;
    @FXML
    private TableColumn<StudentData, Long> studentIdColumn;
    @FXML
    private TableColumn<StudentData, String> studentNameColumn;
    @FXML
    private TableColumn<StudentData, String> studentInstructorColumn;
    @FXML
    private TableColumn<StudentData, String> studentMajorColumn;
    @FXML
    private TableColumn<TeacherData, Long> teacherIdColumn;
    @FXML
    private TableColumn<TeacherData, String> teacherNameColumn;
    @FXML
    private TableColumn<TeacherData, String> teacherCollegeColumn;

    private ObservableList<StudentData> studentData;
    private ObservableList<TeacherData> teacherData;
    private static Student student = new Student();
    private static Teacher teacher = new Teacher();

    private StudentDao studentDao = (StudentDao) ApplicationContextFactory.getApplicationContext().getBean("studentDao");
    private TeacherDao teacherDao = (TeacherDao) ApplicationContextFactory.getApplicationContext().getBean("teacherDao");

    @FXML
    private void initialize() {
        initData();

        //初始化student表
        studentIdColumn.setCellValueFactory(new PropertyValueFactory<StudentData, Long>("id"));
        studentNameColumn.setCellValueFactory(new PropertyValueFactory<StudentData, String>("name"));
        studentInstructorColumn.setCellValueFactory(new PropertyValueFactory<StudentData, String>("teacherName"));
        studentMajorColumn.setCellValueFactory(new PropertyValueFactory<StudentData, String>("major"));
        studentTableView.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                StudentData selectedStudent = studentTableView.getSelectionModel().getSelectedItem();
                if(selectedStudent != null) {
                    student.setMajor(selectedStudent.getMajor());
                    student.setId(selectedStudent.getId());
                    student.setName(selectedStudent.getName());
                    teacher.setToEmpty();
                    modifyButton.setDisable(false);
                    deleteButton.setDisable(false);
                    chooseTeacherButton.setDisable(false);
                    chooseStudentButton.setDisable(true);
                }
            }
        });

        //初始化teacher表
        teacherIdColumn.setCellValueFactory(new PropertyValueFactory<TeacherData, Long>("id"));
        teacherNameColumn.setCellValueFactory(new PropertyValueFactory<TeacherData, String>("name"));
        teacherCollegeColumn.setCellValueFactory(new PropertyValueFactory<TeacherData, String>("college"));
        teacherTableView.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                TeacherData selectedTeacher = teacherTableView.getSelectionModel().getSelectedItem();
                if(selectedTeacher != null) {
                    teacher.setId(selectedTeacher.getId());
                    teacher.setName(selectedTeacher.getName());
                    teacher.setCollege(selectedTeacher.getCollege());
                    student.setToEmpty();
                    modifyButton.setDisable(false);
                    deleteButton.setDisable(false);
                    chooseStudentButton.setDisable(false);
                    chooseTeacherButton.setDisable(true);
                }
            }
        });

        //初始化按钮状态
        deleteButton.setDisable(true);
        modifyButton.setDisable(true);
        chooseStudentButton.setDisable(true);
        chooseTeacherButton.setDisable(true);
    }

    public void initData(){
        studentData = FXCollections.observableArrayList();
        List<Student> students = studentDao.listStudents();
        List<StudentData> studentDatas = new ArrayList<>(students.size());
        students.forEach(s->{
            studentDatas.add(new StudentData(s));
        });
        studentData.addAll(studentDatas);
        studentTableView.setItems(studentData);

        teacherData = FXCollections.observableArrayList();
        List<Teacher> teachers = teacherDao.listTeachers();
        ArrayList<TeacherData> teacherDatas = new ArrayList<>(teachers.size());
        teachers.forEach(t->{
            teacherDatas.add(new TeacherData(t));
        });
        teacherData.addAll(teacherDatas);
        teacherTableView.setItems(this.teacherData);

    }
    private Stage newWindow(String title, int width, int height) {
        Stage window = new Stage();
        window.setTitle(title);
        window.initModality(Modality.APPLICATION_MODAL);
        window.setMinWidth(width);
        window.setMinHeight(height);
        return window;
    }

    private void addComponents(Stage window, Node... components) {
        VBox layout = new VBox(10);
        layout.getChildren().addAll(components);
        layout.setAlignment(Pos.CENTER);

        Scene scene = new Scene(layout);
        window.setScene(scene);
        window.showAndWait();
    }

    private void addOrModifyStudent(boolean add) {
        Stage window = newWindow(add ? "添加学生信息" : "修改学生信息", 200, 300);
        Label nameTip = new Label("输入学生名字：");
        TextField name = new TextField(student.getName());
        name.setPrefHeight(30);
        Label majorTip = new Label("输入学生专业：");
        TextField major = new TextField(student.getMajor());
        major.setPrefHeight(30);

        Button button = new Button("完成");
        button.setOnAction(e -> {
            student.setName(name.getText());
            student.setMajor(major.getText());
            boolean res = add ? studentDao.addStudent(student) : studentDao.updateStudent(student);
            student.setToEmpty();
            initData();
            window.close();
        });

        addComponents(window, nameTip, name, majorTip, major, button);
    }

    @FXML
    private void addStudent(){
        addOrModifyStudent(true);
    }

    @FXML
    private void addTeacher(){
        addOrModifyTeacher(true);
    }
    @FXML
    private void modify(){
        if(student.getId() != null) {
            addOrModifyStudent(false);
        }
        else {
            addOrModifyTeacher(false);
        }
    }

    private void addOrModifyTeacher(boolean add) {
        Stage window = newWindow(add ? "添加教师信息" : "修改教师信息", 200, 300);
        Label nameTip = new Label("输入教师名字：");
        TextField name = new TextField();
        name.setPrefHeight(30);
        Label collageTip = new Label("输入教师院系：");
        TextField collage = new TextField();
        collage.setPrefHeight(30);

        Button button = new Button("完成");
        button.setOnAction(e -> {
            teacher.setName(name.getText());
            teacher.setCollege(collage.getText());
            boolean res = add ? teacherDao.addTeacher(teacher) : teacherDao.updateTeacher(teacher);
            teacher.setToEmpty();
            initData();
            window.close();
        });

        addComponents(window, nameTip, name, collageTip, collage, button);
    }

    @FXML
    private void delete(){
        if(student.getId() == null){
            teacherDao.deleteTeacher(teacher.getId());
        }else {
            studentDao.deleteStudentById(student.getId());
        }
        initData();
    }

    @FXML
    private void chooseInstructor(){
        Stage window = newWindow("选择指导老师", 300, 300);
        try {
            Parent root = FXMLLoader.load(getClass().getResource("mybatis/SelectTeacher.fxml"));
            window.setScene(new Scene(root, 300, 300));
        } catch (IOException e) {
            e.printStackTrace();
        }
        window.showAndWait();
        initData();
    }

    @FXML
    private void chooseStudent(){
        Stage window = newWindow("选择指导学生", 300, 300);
        try {
            Parent root = FXMLLoader.load(getClass().getResource("mybatis/SelectStudent.fxml"));
            window.setScene(new Scene(root, 300, 300));
        } catch (IOException e) {
            e.printStackTrace();
        }
        window.showAndWait();
        initData();
    }

    public static Student getStudent() {
        return student;
    }

    public static void setStudent(Student student) {
        SpringMybatisController.student = student;
    }

    public static Teacher getTeacher() {
        return teacher;
    }

    public static void setTeacher(Teacher teacher) {
        SpringMybatisController.teacher = teacher;
    }
}
